/*
 * @Description: 用户管理
 * @Author: ldx
 * @Date: 2022-09-17 21:22:28
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 23:22:14
 */
import { useAntdTable, useRequest } from 'ahooks'
import {
  Button,
  Col,
  div,
  Form,
  Input,
  Modal,
  Popconfirm,
  Row,
  Select,
  Table
} from 'antd'
const { Option } = Select
import moment from 'moment'
import { useState } from 'react'

import {
  createRole,
  deleteRole,
  queryAccess,
  queryDetails,
  queryRoleList,
  relateAccess,
  updateRole
} from '@/api/setting/role'
import AuthButton from '@/components/authButton'
import { PageContainer } from '@/components/pageContainer'
const Role = () => {
  const [form] = Form.useForm()
  const [roleForm] = Form.useForm()
  const [addForm] = Form.useForm()
  const [accessList, setAccessList] = useState<any>([]) // 权限列表
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpenRole, setIsModalOpenRole] = useState(false)
  const [isModalOpenDetails, setIsModalOpenDetails] = useState(false)
  const [role, setRole] = useState<any>()
  const [details, setDetails] = useState<any>({})

  /** 角色分页列表 */
  const { tableProps, search } = useAntdTable(queryRoleList, {
    form
  })

  /** 角色删除 */
  const { runAsync: runDeleteRole } = useRequest(deleteRole, {
    manual: true,
    onSuccess: () => {
      search.submit()
    }
  })
  /** 角色关联权限 */
  const { runAsync: runRelateAccess } = useRequest(relateAccess, {
    manual: true,
    onSuccess: () => {
      setIsModalOpenRole(false)
      setRole(undefined)
      search.submit()
    }
  })
  /** 角色详情 */
  const { runAsync: runQueryDetails } = useRequest(queryDetails, {
    manual: true,
    onSuccess: (res) => {
      setDetails(res.data)
    }
  })
  /** 创建角色 */
  const { runAsync: runCreateRole } = useRequest(createRole, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
    }
  })
  /** 更新角色 */
  const { runAsync: runUpdateRole } = useRequest(updateRole, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setRole(undefined)
      setIsModalOpen(false)
      addForm.resetFields()
    }
  })
  /** 权限列表 */
  useRequest(queryAccess, {
    onSuccess: (res) => {
      setAccessList(res.data)
    }
  })
  const columns: any[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'a',
      render: (text: string, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '角色名称',
      align: 'center',
      dataIndex: 'roleName'
    },
    {
      title: '角色描述',
      align: 'center',
      dataIndex: 'description'
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      render: (text: string) => {
        return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'creatorName'
    },
    {
      title: '操作',
      width: 300,
      align: 'center',
      key: 'action',
      render: (text: number, record: any) => (
        <div>
          <AuthButton
            auth={['/**', '/role/**', '/role/details/{id}']}
            type="link"
            onClick={() => {
              setIsModalOpenDetails(true)
              runQueryDetails(record.id)
            }}
          >
            详情
          </AuthButton>
          <AuthButton
            type="link"
            auth={['/**', '/role/**', '/role/relate-access/{id}']}
            onClick={() => {
              setRole(record)
              setIsModalOpenRole(true)
              roleForm.setFieldsValue({
                accessIds: record.accessIds.map(String)
              })
            }}
          >
            关联权限
          </AuthButton>
          <AuthButton
            type="link"
            auth={['/**', '/role/**', '/role/update']}
            onClick={() => {
              setRole(record)
              addForm.setFieldsValue(record)
              setIsModalOpen(true)
            }}
          >
            编辑
          </AuthButton>
          <Popconfirm
            title="确认删除角色?"
            onConfirm={() => runDeleteRole(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={['/**', '/role/**', '/role/delete/{id}']}
              type="link"
            >
              删除
            </AuthButton>
          </Popconfirm>
        </div>
      )
    }
  ]
  return (
    <>
      <PageContainer>
        <div>
          <Form form={form}>
            <Row gutter={24}>
              <Col span={5}>
                <Form.Item name="keyword">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={() => search.submit()} type="primary">
                  搜索
                </Button>
              </Col>
              <Col span={11} className="flex justify-end">
                <AuthButton
                  auth={['/**', '/role/**', '/role/create']}
                  onClick={() => setIsModalOpen(true)}
                  type="primary"
                >
                  创建
                </AuthButton>
              </Col>
            </Row>
          </Form>
          <Table
            columns={columns}
            scroll={{ x: 1400 }}
            rowKey={(record) => record.id}
            {...tableProps}
            pagination={{
              showTotal: (total, range) => {
                console.log('xxx', range)
                const num = Math.ceil(total / 10)
                return (
                  <span style={{ color: '#fff', marginRight: '10px' }}>
                    共{num}页/共{total}条结果
                  </span>
                )
              },
              ...tableProps.pagination
            }}
          />
        </div>
      </PageContainer>
      <Modal
        width={800}
        title="关联权限"
        visible={isModalOpenRole}
        onOk={() => {
          roleForm.validateFields().then((valuse) => {
            runRelateAccess(role.id, valuse.accessIds)
          })
        }}
        onCancel={() => {
          setIsModalOpenRole(false)
          setRole(undefined)
        }}
      >
        <Form form={roleForm}>
          <Form.Item
            name="accessIds"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              placeholder="请选择角色"
              style={{ width: '100%' }}
              mode="multiple"
            >
              {accessList.map((item: any) => {
                return (
                  <Option key={item.id} value={`${item.id}`}>
                    {item.accessName}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        width={800}
        title="角色详情"
        visible={isModalOpenDetails}
        onOk={() => {
          setIsModalOpenDetails(false)
          setRole(undefined)
        }}
        onCancel={() => {
          setIsModalOpenDetails(false)
          setRole(undefined)
        }}
      >
        <div>
          <div>
            <span className="w-120px inline-block mt-10px">角色名称：</span>
            <span>{details.roleName}</span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">关联权限：</span>
            <span>
              {(details.accesses || [])
                .map((item: any) => item.accessName)
                .join('、')}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">创建时间：</span>
            <span>
              {moment(details.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">创建人：</span>
            <span>{details.creatorName}</span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新时间：</span>
            <span>
              {details?.updateTime
                ? moment(details?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                : ''}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新人：</span>
            <span>{details?.updateName}</span>
          </div>
          <div>
            <span className="w-120px inline-block mt-10px">描述：</span>
            <span>{details.description}</span>
          </div>
        </div>
      </Modal>
      <Modal
        width={800}
        title={role ? '编辑角色' : '新增角色'}
        visible={isModalOpen}
        onOk={() => {
          addForm.validateFields().then((values) => {
            if (role) {
              runUpdateRole({ ...role, ...values })
            } else {
              runCreateRole(values)
            }
          })
        }}
        onCancel={() => {
          setIsModalOpen(false)
          setRole(undefined)
          addForm.resetFields()
        }}
      >
        <div>
          <Form
            name="register"
            initialValues={{
              prefix: '86'
            }}
            form={addForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              name="roleName"
              label="角色名称"
              rules={[{ required: true, message: '请输入角色名称' }]}
            >
              <Input></Input>
            </Form.Item>
            <Form.Item
              name="description"
              label="描述"
              rules={[{ required: true, message: '请输入角色描述' }]}
            >
              <Input></Input>
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </>
  )
}

export default Role
